package com.huayanginfo.saas.datasource;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.lang.RandomStringUtils;

import com.huayanginfo.saas.domain.member.User;

/**
 * 连接信息工厂
 * @author rabbit
 *
 */
public class ConnectionStrategy {

	private ConnectionStrategy() {
		throw new AssertionError();
	}
	
	public static ConnectionInfo generateConnectionInfo(User user) {
		ConnectionInfo connectionInfo = new ConnectionInfo();
		connectionInfo.setDatabaseName(generateDBName(user));
		connectionInfo.setPassword(generateDBPassword());
		connectionInfo.setUsername(generateDBUserName(user));
		connectionInfo.setJndiURL(generateJNDIKey(user));
		return connectionInfo;
	}
	
	public static String generateDBUserName(User user) {
		return RandomStringUtils.randomAlphabetic(16);
	}
	
	public static String generateDBName(User user) {
		return user.getEmail().replaceAll("\\.", "_dot_").replaceAll("@", "_at_");
	}
	
	public static String generateDBPassword() {
		return RandomStringUtils.randomAlphanumeric(10);
	}
	
	public static String generateJNDIKey(User user){
		//return "jdbc/" + user.getEmail();
		return user.getEmail();
	}
	
	/**
	 * 为数据源增加用户名、密码及数据库信息
	 * @param connectionInfo
	 * @param dataSource
	 */
	public static void reConfigDataSource(ConnectionInfo connectionInfo, BasicDataSource dataSource) {
		String url = dataSource.getUrl();
		url = url.endsWith("/") ? url: url + "/";
		dataSource.setUrl(url + connectionInfo.getDatabaseName());
		dataSource.setUsername(connectionInfo.getUsername());
		dataSource.setPassword(connectionInfo.getPassword());
	}
	
	public static String getDBIp(String datasourceURL) {
		Pattern pattern = Pattern.compile(".*?((\\d+\\.){3}\\d+).*");
		Matcher matcher = pattern.matcher(datasourceURL);
		String string = null;
		if (matcher.matches()) {
		string = datasourceURL.substring(matcher.start(1), matcher.end(1));}
		return string;
	}

	public static String getHostIp() throws UnknownHostException {
		InetAddress inetAddress = InetAddress.getLocalHost();
		return inetAddress.getHostAddress();
	}

	public static String getConnectionIp() throws UnknownHostException {
		String hostIp = getHostIp();
		int index = hostIp.lastIndexOf(".");
		String allowedIp = hostIp.substring(0, index) + ".%";
		return allowedIp;
	}
}
